//
//  AddThirdCheckViewController.m
//  PatientApp
//
//  Created by chirui on 2017/7/11.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "AddThirdCheckViewController.h"



@interface AddThirdCheckViewController ()
{
    NSArray * peopleArray;
    NSString * peopleId;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UITextField *valueText;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *upLoadImage;
@property (weak, nonatomic) IBOutlet UILabel *oneTitle;
@property (weak, nonatomic) IBOutlet UILabel *twoTitle;
@property (weak, nonatomic) IBOutlet UITextField *moneyText;


@end

@implementation AddThirdCheckViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatScrollView];
    TitleView(@"申请互助");
    self.imageArray = @[].mutableCopy;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
    
    self.valueText.delegate = self;
    [self creatEndView];
    [self getChoosePeopleRequest];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    if (textField == self.valueText) {
        [textField resignFirstResponder];
        
        if (peopleArray.count>0) {
            
            NSMutableArray * array = @[].mutableCopy;
            if (array) {
                
                [array removeAllObjects];
            }
            
            for (NSDictionary * dic in peopleArray) {
              
                    [array addObject:dic[@"name"]];
                }
    
        zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:array andHeadTitle:@"申请人" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
            
            _valueText.text = choiceString;
            [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                
                
                if ([obj isEqualToString:choiceString]) {
                    
                    peopleId = peopleArray[idx][@"id"];

                    NSLog(@"%@-索引%d 对应id== %@",obj, (int)idx,peopleId);
                }
            }];
            
            [pickerView dismissPicker];
            
        }];
        [pickerView show];
        }else {
            
            [self getChoosePeopleRequest];
        }
    }
   
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)creatEndView{
    
    UIView * endView =[[UIView alloc]init];
    
    if (ISPX) {
        endView.frame = CGRectMake(0, HEIGHT-64-48-34, WIDTH, 48+32);
    }else{
        endView.frame = CGRectMake(0, HEIGHT-64-48, WIDTH, 48);
    }
    endView.backgroundColor = NavBackColor;
    
    UIButton * endBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    endBtn.frame = CGRectMake(0, 0, WIDTH, 48);
    endBtn.backgroundColor = NavBackColor;
    [endBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [endBtn setTitle:@"提交" forState:UIControlStateNormal];
    [endBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [endView addSubview:endBtn];
    [self.view addSubview:endView];
}

-(void)addBtnClick {
    
    if (self.valueText.text.length == 0||self.valueText.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请选择申请人");
        return;
    }
    if (self.moneyText.text.length == 0||self.moneyText.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请输入申请金额");
        return;
    }
    
    if (self.contentTextView.text.length == 0||self.contentTextView.text==nil) {
        
        self.contentTextView.text=@"请输入申请描述";
        return;
    }
    
    if (self.imageArray.count>0) {
        
        [self upIconImageRequest];
        
    }else{
        
        self.contentTextView.text=@"请上传申请资料";
        return;
    }

}


-(void)creatScrollView {
    
    _scrollView.showsVerticalScrollIndicator =NO;
    _scrollView.contentSize = CGSizeMake(WIDTH, 700);
    _scrollView.userInteractionEnabled=YES;
    _scrollView.scrollEnabled =YES;
    _scrollView.backgroundColor = [UIColor whiteColor];
    
    
    self.contentTextView = [[SZTextView alloc]initWithFrame:CGRectMake(20,CGRectGetMaxY(self.twoTitle.frame)+30 , WIDTH - 30, 120)];
    self.contentTextView.font = [UIFont systemFontOfSize:15];
    self.contentTextView.placeholder = @"请填写申请描述";
    [self.bgView addSubview:self.contentTextView];
    
    
    
    // 选择的图片
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    CGFloat margin = 6;
    CGFloat lenth = (WIDTH-20-margin*2)/3;
    flowLayout.itemSize = CGSizeMake(lenth, lenth);
    flowLayout.minimumLineSpacing = margin;
    flowLayout.minimumInteritemSpacing = margin;
    self.imageCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    self.imageCollectionView.backgroundColor = [UIColor whiteColor];
    self.imageCollectionView.scrollEnabled = NO;
    [self.bgView addSubview:self.imageCollectionView];
    [self.imageCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.upLoadImage.mas_bottom).offset(10);
        make.left.equalTo(self.bgView).offset(10);
        make.right.equalTo(self.bgView).offset(-10);
        make.height.mas_equalTo(margin * 2 + lenth * 3);
    }];
    // 代理&注册cell
    self.imageCollectionView.dataSource = self;
    self.imageCollectionView.delegate = self;
    [self.imageCollectionView registerClass:[ReleaseImageItemCell class] forCellWithReuseIdentifier:@"ReleaseImageItemCell"];
    
}

#pragma mark - 选择图片
// 配置图片选择器
- (void)configImageSelector {
    if(!self.imagePicker) {
        self.imagePicker = [[TZImagePickerController alloc]initWithMaxImagesCount:9 delegate:self];
        self.imagePicker.allowPreview = NO;
        self.imagePicker.alwaysEnableDoneBtn = YES;
        self.imagePicker.allowPickingOriginalPhoto = NO;
        self.imagePicker.allowPickingGif = NO;
        self.imagePicker.allowPickingVideo = NO;
        self.imagePicker.allowPickingImage = YES;
    }
    self.imagePicker.maxImagesCount = 6 - self.imageArray.count;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    [picker dismissViewControllerAnimated:YES completion:nil];
    // 获取图片
    for(UIImage *image in photos) {
        [self.imageArray addObject:image];
    }
    
    [self.imageCollectionView reloadData];
}
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - uicollectionview datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if(self.imageArray.count < 6) {
        return self.imageArray.count + 1;
    }else {
        return 6;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ReleaseImageItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ReleaseImageItemCell" forIndexPath:indexPath];
    // 配置添加照片按钮
    if(indexPath.item == self.imageArray.count) {
        [cell.cancelButton setHidden:YES];
        cell.imageView.image = [UIImage imageNamed:@"img_help_add_pt"];
        return cell;
    }
    // 显示删除按钮
    [cell.cancelButton setHidden:NO];
    // 配置cell数据
    cell.indexPath = indexPath;
    cell.preVC = self;
    
    cell.imageView.image = self.imageArray[indexPath.item];
    
    return cell;
}

// 选中的item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.item == self.imageArray.count) {
        self.imagePicker = nil;
        [self configImageSelector];
    }
}


-(void)getChoosePeopleRequest{
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,get_memberList_api];
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"status":@"effective"
                           };

    [PostNetWorking postNetWorkingStr:parametersStr andparameters:dic Success:^(id responseObject) {
        
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]== 200) {
            if ([responseObject[@"datas"] isKindOfClass:[NSArray class]]) {
                 peopleArray = responseObject[@"datas"];
                
                if (peopleArray.count==0) {
                    
                    SHuiMBhudTextTimeStr(@"还没有申请人可以选择");
                }
            }
        }else{

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

    } failed:^(NSError *error) {

        SHuiMBHidleYes;

        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
        
    }];
    
}

// 有照片的
-(void)upIconImageRequest{
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,add_helpApply_api];
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"money":self.moneyText.text,
                           @"content":self.contentTextView.text,
                           @"id":peopleId
                           };
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    SHuiMBhubNoTimeStr(@"正在提交...");
    [manager POST:parametersStr parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        for(int i = 0; i < self.imageArray.count; i++) {
            
            
            NSData *data = UIImageJPEGRepresentation(self.imageArray[i], 0.4);
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@%d.png", str,i];
//            NSString * imageName = [NSString stringWithFormat:@"img_src%d",i];
            [formData appendPartWithFileData:data name:@"image" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            
            
            SHuiMBhudTextTimeStr(@"提交成功");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
            
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
        
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
        
    } ];
    
}





@end
